package controller

import (
	"barrage-go/common"
	"barrage-go/consts"
	"barrage-go/proto/pb"
	"barrage-go/service"
	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"time"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:   1024,
	WriteBufferSize:  1024,
	HandshakeTimeout: time.Second * 10,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SocketHandler(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("升级websocket过程发生异常:", err)
	}

	ws.SetCloseHandler(func(code int, text string) error {
		log.Println("接收到的code:", code, "内容为:", text)
		ws.Close()
		return nil
	})

	//go service.Ping(ws)
	receiveMsg(ws)

}

func receiveMsg(ws *websocket.Conn) {
	defer ws.Close()

	for {
		_, message, err := ws.ReadMessage()

		if err != nil {
			log.Println("读取消息发生异常:", err)
			common.RemoveClient(ws)
			break
		}

		barrage := &pb.Barrage{}
		err1 := proto.Unmarshal(message, barrage)
		if err1 != nil {
			log.Println("解析protocol buffer 发生异常:", err1)
			continue
		}
		log.Println("接收到信息：", barrage.MsgType)

		switch barrage.MsgType {
		case consts.WebClientLoginReq:
			service.WebClientLoginReq(barrage.BytesData, ws)
		case consts.WebClientBarrageHistoryReq:
			service.WebClientBarrageHistoryReq(barrage.BytesData, ws)
		case consts.WebClientBarrageMsgRollingReq:
			service.WebClientBarrageMsgRollingReq(barrage.BytesData, ws)
		case consts.WebClientHeartBeatReq:
			service.WebClientHeartBeatReq(barrage.BytesData, ws)
		case consts.WebClientBarrageReq:
			service.WebClientBarrageReq(barrage.BytesData, ws)

		default:
			log.Println("未知请求")

		}

	}
}
